import { EBundleType, ESkeNameType, EViewType } from "../../Common/Enum";
import { ISayConfig, TalkModule } from "../../Common/TalkModule";
import { IBaseSkeData, IMessage, IViewData } from "../../Interface/IMessage";
import { ELayerType, SceneGame } from "../../SceneGame";
import GameUtil from "../../Util/GameUtil";
import BaseDrag from "../../Base/BaseDrag";
import ItemDrag, { EDragType } from "./ItemDrag";
import AppService from "../../Service/AppService";
import StorageUtil from "../../Util/StorageUtil";
import AudioManager from "../../Util/AudioManager";

const { ccclass, property } = cc._decorator;

const VIEW_DATA: IViewData = {
    name: 'LayerStory2',
    type: EViewType.Layer,
    bundle: EBundleType.Story,
    zIndex: 100,
};

@ccclass
export default class LayerStory2 extends BaseDrag {
    public static instance: LayerStory2 = null;

    @property({ type: cc.Node, tooltip: "人物剪影" })
    private shadows: cc.Node = null;
    @property({ type: [cc.Node], tooltip: "spine动画" })
    private skes: cc.Node[] = [];
    @property({ type: cc.Node, tooltip: "点击收集" })
    private clicks: cc.Node = null;

    @property({ type: cc.Node, tooltip: "icon根节点" })
    private icons: cc.Node = null;
    @property({ type: cc.Node, tooltip: "icon" })
    public icon: cc.Node = null;

    @property({ type: cc.Node, tooltip: "上划提示节点" })
    private huaTipSke: cc.Node = null;

    private startId: number = 101;
    private dragType: EDragType = EDragType.Drag;
    private isHuaTip: boolean = true;

    private dragNames: string[] = ['顾浩(弟弟)'];
    private clickNames: string[] = ['得意的弟弟', '伤心的顾母', '失意的男主'];

    protected onLoad() {
        super.onLoad();

        LayerStory2.instance = this;

        this.rootScale = SceneGame.instance.getRootScale();

        this.showHuaTip();
        this.initShadowIcons();

        this.changeGuMuAnim(ESkeNameType.GuMuKu2);
        this.changeGuYunZeAnim(ESkeNameType.GuIdle);
    }

    private showHuaTip() {
        if (this.isHuaTip) {
            this.isHuaTip = false;
            this.huaTipSke.active = true;
        }
    }

    private hideHuaTip() {
        this.huaTipSke.active = false;
    }

    private initShadowIcons() {
        this.dragType = EDragType.Drag;
        this.icons.active = true;
        this.clicks.active = false;
        for (let i = 0; i < this.skes.length; i++) {
            const node = this.skes[i];
            node.active = false;
        }
        for (let i = 0; i < this.shadows.children.length; i++) {
            const node = cc.instantiate(this.icon);
            node.parent = this.icons;
            node.getComponent(ItemDrag).setData({ id: i + this.startId, index: i, type: EDragType.Drag, name: this.dragNames[i] });
        }
        this.icon.getComponent(ItemDrag).setData({ id: -1, index: -1, type: EDragType.Drag, name: '' });
    }

    private initClickIcons() {
        this.dragType = EDragType.Click;
        this.clicks.active = true;

        for (let i = this.icons.children.length - 1; i > -1; i--) {
            this.icons.children[i].destroy();
        }

        for (let i = 0; i < this.clicks.children.length; i++) {
            const node = cc.instantiate(this.icon);
            node.parent = this.icons;
            node.y = 0;
            const comp = node.getComponent(ItemDrag);
            comp.setData({ id: i + this.startId, index: i, type: EDragType.Click, name: this.clickNames[i] });
        }
    }

    private clicked: number[] = [-1, -1, -1];
    private getClickData(): { nodes: cc.Node[], callback: Function } {
        let self = this;
        let data: { nodes: cc.Node[], callback: Function } = { nodes: null, callback: null };
        if (this.clicks.active) {
            data.nodes = this.clicks.children;
            data.callback = async (node: cc.Node, index: number) => {
                const id = index + self.startId;
                if (self.clicked[index] > -1) {
                    return;
                }
                self.clicked[index] = 1;
                // 显示icon图片
                this.icons.children[index].getComponent(ItemDrag).showIcon(index);
                // 顾浩抓动作
                if (id === 101) {
                    this.changeGuErAnim('er_zhua');
                    await GameUtil.sleep(1200);
                    this.changeGuErAnim('er_idle_say');
                } else if (id === 103) {
                    this.changeGuYunZeAnim('gu_bugan_idle');
                }
                // 气泡对话
                TalkModule.updateStoryBubble(id, this.talkComplete.bind(this));
            }
        } else {
            // 先判断在滑动区域内?
            const isInter = GameUtil.intersect(this.clickRect, this.icons);
            if (!isInter) return null;
            data.nodes = this.icons.children;
            data.callback = (node: cc.Node, index: number) => {
                // 设置点击数据
                self.touchData = {
                    id: node.getComponent(ItemDrag).getId(),
                    node: node,
                    isMove: false,
                }
            }
        }
        return data;
    }

    private talkComplete(id: number) {
        switch(id) {
            case 101:     // 富豪说完
                this.changeGuErAnim('er_idle');
                break;
            case 103:
                this.changeGuYunZeAnim('gu_luopo_idle');
                break;
        }


        let isComplete = true;
        for (let i = 101; i < 104; i++) {   // 前情2
            const talk = TalkModule.getSayConfigById(i);
            if (!talk.isComplete) {
                isComplete = false;
                break;
            }
        }

        if (isComplete && this.dragType === EDragType.Click) {
            this.dragType = EDragType.Default;
            this.icons.active = false;
            this.icons.removeAllChildren();

            // 完成前情
            const talkData = StorageUtil.instance.getTalkData();
            talkData.id = 10001;
            SceneGame.instance.showLayer(ELayerType.LayerGame);
        }
    }

    private startY: number;
    private touchData: { id: number, node: cc.Node, isMove: boolean } = { id: -1, node: null, isMove: false };
    public touchStart(event: cc.Event.EventTouch) {
        const pos = this.getClickPos(event);
        this.startY = pos.y;
        const data = this.getClickData();
        for (let i = 0; i < data?.nodes?.length; i++) {
            // TODO 需要先点顾二和顾母才能点男主
            if (data.nodes[i] === this.clicks.children[2]) {
                if (this.clicked[0] <= -1 || this.clicked[1] <= -1) {
                    return;
                }
            }

            const intersect = GameUtil.intersect(this.clickRect, data.nodes[i]);
            if (intersect) {
                if (this.dragType === EDragType.Drag) {
                    const icon = cc.find("icon", data.nodes[i]);
                    if (icon?.active) {
                        data.callback && data.callback(data.nodes[i], i);
                        data.callback = null;
                    }
                } else {
                    data.callback && data.callback(data.nodes[i], i);
                    data.callback = null;
                }
            }
        }
    }

    public touchMove(event: cc.Event.EventTouch) {
        if (this.dragType !== EDragType.Drag) return;

        const pos = this.getClickPos(event);
        if (this.touchData.id > -1 && Math.abs(this.clickRect.y - this.startY) > 50) {
            this.touchData.isMove = true;
            this.setMoveIconPos();
        } else {
            if (!this.touchData.isMove) {
                // const x = this.contentPos.x + (nowPos.x - startPos.x);
                // this.icons.getComponent(ScrollContent).set(this.icons, x);
            } else {
                this.setMoveIconPos();
            }
        }
    }

    public touchEnd(event: cc.Event.EventTouch) {
        const index = this.touchData.id - this.startId;
        const shadow = this.shadows.children[index];
        const isInter = GameUtil.intersect(this.clickRect, shadow);
        if (isInter) {
            shadow.active = false;
            this.changeGuErAnim('er_idle');
            this.destroyIcon();
        }

        // 重置
        this.icon.x = -1000;
        this.clickRect.x = -1000;
        this.touchData = { id: -1, node: null, isMove: false };

        setTimeout(() => {
            const isComplete = this.getIsComplete();
            if (isComplete && this.dragType === EDragType.Drag) {
                this.initClickIcons();
            }
        }, 1000 / 60);
    }

    private destroyIcon() {
        for (let i = 0; i < this.icons.children.length; i++) {
            const temp = this.icons.children[i];
            const touch = this.touchData.node;
            if (temp === touch) {
                // temp.destroy();
                cc.find("icon", touch).active = false;
            }
        }
        // 完成一个后隐藏提示
        this.hideHuaTip();
    }

    private zhuaCount: number = 0;
    private changeGuErAnim(name: ESkeNameType | string) {
        const node = this.skes[0];
        const ske = node.getComponent(sp.Skeleton);
        node.active = true;

        const data: IBaseSkeData = {
            ske: ske,
            animName: name,
            isLoop: true,
        }
        if (name === 'er_zhua') {
            AudioManager.instance.playSound('前情撕衣服声');
            this.zhuaCount++;
            data.isLoop = false;
            data.timeScale = 2;
            data.callback = () => {
                if (this.zhuaCount >= 2) {
                    this.changeGuErAnim('er_idle');
                } else {
                    this.changeGuErAnim('er_zhua');
                }
            }

            if (this.zhuaCount == 1) {
                this.changeGuYunZeAnim(ESkeNameType.GuBeiSi);
            }
        }
        
        GameUtil.playAnimation(data);
    }

    public changeGuYunZeAnim(name: ESkeNameType | string) {
        const node = this.skes[1];
        const ske = node.getComponent(sp.Skeleton);
        node.active = true;

        const data: IBaseSkeData = {
            ske: ske,
            animName: name,
            isLoop: true,
            hideBones: ["顾嘴"],
        }

        if (name === ESkeNameType.GuBeiSi) {
            data.isLoop = false;
            data.callback = () => {
                this.changeGuYunZeAnim(ESkeNameType.GuLuoPoIdle);
            }
        } else if (name === 'gu_bugan_idle') {
            data.showBones = ["顾嘴"];
        }
        GameUtil.playAnimation(data);
    }

    public changeGuMuAnim(name: ESkeNameType) {
        const node = this.skes[2];
        const ske = node.getComponent(sp.Skeleton);
        node.active = true;

        const data: IBaseSkeData = {
            ske: ske,
            animName: name,
            isLoop: true,
            hideBones: ["hand2"],
        }

        if (name === ESkeNameType.GuMuKu2) {
            data.callback = () => { }
            GameUtil.playAnimation(data);
        }
    }

    /** 设置拖动中的icon位置 */
    private setMoveIconPos() {
        this.icon.getComponent(ItemDrag).setData({ id: this.touchData.id, index: -1, type: EDragType.Drag, name: '' });
        this.icon.setPosition(cc.v2(this.clickRect.x, this.clickRect.y));
    }

    /**
     * 获取拖拽/点击全部完成?
     * @returns 
     */
    public getIsComplete() {
        if (this.dragType === EDragType.Drag) {
            let count = 0;
            for (let i = 0; i < this.icons.children.length; i++) {
                const node = this.icons.children[i];
                const icon = cc.find("icon", node);
                if (icon.active) {
                    count++;
                }
            }
            return count === 0;
        } else if (this.dragType === EDragType.Click) {
            const length = this.icons.children.length;
            const tempArr = this.clicked.filter((o) => o == 1);
            return tempArr.length === length;
        }
    }

    public getViewData() {
        return VIEW_DATA;
    }
}
AppService.instance.registViewData(VIEW_DATA);